<template>
  <router-view />
</template>

<script setup>
import { onMounted, ref } from "vue";
import { useStore } from "vuex";
import { addExp } from "@/api/user";

const store = useStore();

// 记录用户上次访问时间
const lastVisitTime = ref(
  localStorage.getItem("lastVisitTime")
    ? new Date(localStorage.getItem("lastVisitTime"))
    : null
);

// 检查是否超过三天未访问
const checkLastVisit = () => {
  if (lastVisitTime.value) {
    const now = new Date();
    const diffTime = Math.abs(now - lastVisitTime.value);
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
    if (diffDays > 3) {
      // 超过三天未访问，清空 userInfo
      store.commit("setUserInfo", null);
      localStorage.removeItem("user");
    }
  }
  // 更新最后访问时间
  const currentTime = new Date();
  lastVisitTime.value = currentTime;
  localStorage.setItem("lastVisitTime", currentTime.toISOString());
};

// 每天 24 点重置 experience 中的值
const resetExperience = () => {
  const checkTime = () => {
    const now = new Date();
    const hours = now.getHours();
    const minutes = now.getMinutes();
    const seconds = now.getSeconds();
    if (hours === 0 && minutes === 0 && seconds === 0) {
      store.commit("resetExperience");
    }
  };
  // 每秒检查一次
  setInterval(checkTime, 1000);
};

const getLoginExp = async () => {
  let first = store.state.experience.visit;
  if (!first) {
    let userId = store.state.userInfo.userId;
    let exp = store.state.visitExperience;
    const response = await addExp(userId, exp);

    if (response && response.state === 0) {
      alert("每日登录，经验值增加 " + exp + " !");
      store.commit("setVisitExperience");
      store.state.experience.visit = true;
    }
  }
};

onMounted(() => {
  checkLastVisit();
  resetExperience();
  // getLoginExp();
  store.commit("setExperience");
});
</script>

<style lang="stylus">
#app
  font-family Avenir, Helvetica, Arial, sans-serif
  -webkit-font-smoothing antialiased
  -moz-osx-font-smoothing grayscale
  text-align center
  color #2c3e50
</style>
